package com.reader.api.interceptor;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.reader.api.entity.usercenter.User;
import com.reader.api.mapper.usercenter.UserMapper;
import com.reader.api.service.usercenter.IUserService;
import com.reader.core.annotation.IgnoreAuth;
import com.reader.core.utils.CommonVariable;
import com.reader.core.utils.JWTUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * add by jiahaikun for UI api 拦截验证TOKEN
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IUserService iUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws  Exception {
        IgnoreAuth annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
        }else{
            return true;
        }

       //如果有@IgnoreAuth注解，则不验证token
        if(annotation != null){
            return true;
        }
       //从header中获取authorization，转成realm可识别的token
        String token = request.getHeader(CommonVariable.TOKEN);
        if(StringUtils.isBlank(token)){
            token = request.getParameter(CommonVariable.TOKEN);
        }

       String loginID= jwtUtil.getLoginId(token);

        //tokoen 不能为空
        if(StringUtils.isBlank(token)) {
            throw new AuthenticationException(CommonVariable.TOKEN+"不能为空!");
        }
        //凭证过期验证
        if (jwtUtil.tokenExpired(token)) {
            throw new AuthenticationException("访问凭证已过期!");
        }

        //从user表中取密码和token中验证比较
        User user=new User();
        user.setMobile(loginID);
        //user= userMapper.selectOne(user);
        EntityWrapper<User> ew = new EntityWrapper<User>();
        user= iUserService.selectOne(ew);
        if (!jwtUtil.tokenVerify(token, loginID, user.getPassword())) {
            throw new AuthenticationException("用户名或密码不正确!");
        }
//        request.setAttribute(CommonVariable.LOGIN_ID,loginID);
        return true;
    }

    @Override
    public void postHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {

    }
    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }

    /**
     * 跨域正常返回到前端，避免前端异常  //20170926 add by jiahaikun
     * @param request
     * @param response
     */
    private  void setAccessControl(HttpServletRequest request, HttpServletResponse response){
        String origin = request.getHeader("Origin");
        response.addHeader("Access-Control-Allow-origin",origin);
        response.addHeader("Access-Control-Allow-Methods","GET, POST, DELETE, PUT,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
        response.addHeader("Access-Control-Allow-Credentials","true");
    }


}
